package alo;

import java.util.*;

/**
 * @ClassName t12
 * @Description TODO
 * @Author Fanxc
 * @DATE 2021/4/21 9:56
 * @Version 1.0
 */


public class t12 {

    private class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode addInList(ListNode head1, ListNode head2) {
        ListNode p1 = Ref(head1);
        ListNode p2 = Ref(head2);
        ListNode head = new ListNode(0);
        int flag = 0;
        while (p1 != null && p2 != null) {
            head.val = (p1.val + p2.val + flag) % 10;
            flag = (p1.val + p2.val + flag) / 10;
            ListNode temp = new ListNode(0);
            temp.next = head;
            head = temp;
            p1 = p1.next;
            p2 = p2.next;
        }

        while (p2 != null) {
            int num = p2.val + flag;
            head.val = num % 10;
            flag = num / 10;
            ListNode temp = new ListNode(0);
            temp.next = head;
            head = temp;
            p2 = p2.next;
        }


        while (p1 != null) {
            int num = p1.val + flag;
            head.val = num % 10;
            flag = num / 10;
            ListNode temp = new ListNode(0);
            temp.next = head;
            head = temp;
            p1 = p1.next;
        }

        if (flag == 0) return head.next;
        head.val = flag;
        return head;
    }

    //逆置链表,返回新的头结点
    private ListNode Ref(ListNode head) {
        if (head == null) return head;

        ListNode temp = null;
        ListNode cur = head;
        ListNode nxt = null;
        while (cur != null) {
            nxt = cur.next;
            cur.next = temp;
            temp = cur;
            cur = nxt;
        }
        return temp;
    }
}

